import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get_navigation/src/root/get_material_app.dart';
import 'package:get/get_navigation/src/routes/transitions_type.dart';
import 'package:mobile_vpn/pages/index/index_binding.dart';
import 'package:mobile_vpn/pages/index/index_page.dart';
import 'package:mobile_vpn/router/router_observer.dart';
import 'package:mobile_vpn/router/routers.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:screen_retriever/screen_retriever.dart';
import 'package:window_manager/window_manager.dart';
import 'package:flutter/foundation.dart';

import 'common/cpn/default_refresh_indicator.dart';
import 'common/utils/injection.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // 窗口管理器初始化（必须放在最前面）
  if (!kIsWeb && (Platform.isMacOS || Platform.isWindows || Platform.isLinux)) {
    await windowManager.ensureInitialized();
  }
  await Hive.initFlutter();
  await Hive.openBox<String>('settings');  // 打开字符串类型的 Box
  await Hive.openBox<int>('selectedIndex');  // 打开整数类型的 Box
  await Injection().init();

  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with WindowListener {
  @override
  void initState() {
    super.initState();
    if (!kIsWeb && (Platform.isMacOS || Platform.isWindows || Platform.isLinux)) {
      windowManager.addListener(this);
      setWindowProperties();
    }
  }

  @override
  void dispose() {
    if (!kIsWeb && (Platform.isMacOS || Platform.isWindows || Platform.isLinux)) {
      windowManager.removeListener(this);
    }
    super.dispose();
  }

  Future<void> setWindowProperties() async {
    await windowManager.ensureInitialized();
    final screen = await ScreenRetriever.instance.getPrimaryDisplay();
    final width = screen.size.width * 0.23;
    final height = screen.size.height * 0.8;

    // 设置窗口大小和固定尺寸
    await windowManager.setSize(Size(width, height));
    await windowManager.setMinimumSize(Size(width, height));
    await windowManager.setMaximumSize(Size(width, height));
    await windowManager.center();
    await windowManager.setAlwaysOnTop(false);
    await windowManager.setTitle(" 快连");
    await windowManager.setMaximizable(false);
    await windowManager.setTitleBarStyle(
      TitleBarStyle.normal,
    );
  }

  @override
  Widget build(BuildContext context) {
    return ScreenUtilInit(
      designSize: const Size(750, 1334),
      builder: (context, child) => _defaultRefreshConfiguration(
        GetMaterialApp(
          showPerformanceOverlay: false,
          getPages: AppRoutes.routerPages,
          navigatorObservers: [AppRouterObserver()],
          defaultTransition: Transition.rightToLeft,
          transitionDuration: const Duration(milliseconds: 150),
          title: "vpn",
          home: IndexPage(),
          initialBinding: IndexBinding(),
          locale: const Locale('zh'),
        ),
      ),
    );
  }

  RefreshConfiguration _defaultRefreshConfiguration(Widget child) {
    return RefreshConfiguration(
      headerBuilder: () => DefaultRefreshHeader(),
      footerBuilder: () => DefaultRefreshFooter(),
      headerTriggerDistance: 180.w,
      maxOverScrollExtent: 100.w,
      maxUnderScrollExtent: 0,
      enableScrollWhenRefreshCompleted: true,
      enableLoadingWhenFailed: true,
      hideFooterWhenNotFull: false,
      enableBallisticLoad: true,
      footerTriggerDistance: 140.w,
      child: child,
    );
  }
}
